<!DOCTYPE html>
<html>
<head>
    

    

    



    <meta charset="utf-8">
    
    
    
    
    <title>JVM基础——类加载器与双亲委派模型 | 博客主页 | 世界是个球，前方总有路！</title>
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    
    <meta name="theme-color" content="#3F51B5">
    
    
    <meta name="keywords" content="JVM">
    <meta name="description" content="一、前言&amp;emsp;&amp;emsp;这是JVM系列博客的第五篇，也是最后一篇，写完这篇博客，我就要暂时停止对JVM的学习，开始学习其他方面的内容了。这篇博客就来说一说JVM中的类加载器，以及类加载的双亲委派模型。   二、正文&amp;emsp;2.1 什么是类加载器&amp;emsp;&amp;emsp;首先我们要知道一件事，那就是什么是类加载器？大家都知道，我们编写的代码需要先被编译为class字节码才能被执行，JVM解">
<meta property="og:type" content="article">
<meta property="og:title" content="JVM基础——类加载器与双亲委派模型">
<meta property="og:url" content="http://tewuyiang.gitee.io/blog/JVM%E5%9F%BA%E7%A1%80%E2%80%94%E2%80%94%E7%B1%BB%E5%8A%A0%E8%BD%BD%E5%99%A8%E4%B8%8E%E5%8F%8C%E4%BA%B2%E5%A7%94%E6%B4%BE%E6%A8%A1%E5%9E%8B/index.html">
<meta property="og:site_name" content="博客主页">
<meta property="og:description" content="一、前言&amp;emsp;&amp;emsp;这是JVM系列博客的第五篇，也是最后一篇，写完这篇博客，我就要暂时停止对JVM的学习，开始学习其他方面的内容了。这篇博客就来说一说JVM中的类加载器，以及类加载的双亲委派模型。   二、正文&amp;emsp;2.1 什么是类加载器&amp;emsp;&amp;emsp;首先我们要知道一件事，那就是什么是类加载器？大家都知道，我们编写的代码需要先被编译为class字节码才能被执行，JVM解">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="http://tewuyiang.gitee.io/blog/JVM%E5%9F%BA%E7%A1%80%E2%80%94%E2%80%94%E7%B1%BB%E5%8A%A0%E8%BD%BD%E5%99%A8%E4%B8%8E%E5%8F%8C%E4%BA%B2%E5%A7%94%E6%B4%BE%E6%A8%A1%E5%9E%8B/1.png">
<meta property="article:published_time" content="2020-03-17T14:46:06.000Z">
<meta property="article:modified_time" content="2020-03-18T12:02:16.971Z">
<meta property="article:author" content="特务依昂">
<meta property="article:tag" content="JVM">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="http://tewuyiang.gitee.io/blog/JVM%E5%9F%BA%E7%A1%80%E2%80%94%E2%80%94%E7%B1%BB%E5%8A%A0%E8%BD%BD%E5%99%A8%E4%B8%8E%E5%8F%8C%E4%BA%B2%E5%A7%94%E6%B4%BE%E6%A8%A1%E5%9E%8B/1.png">
    
        <link rel="alternate" type="application/atom+xml" title="博客主页" href="/blog/atom.xml">
    
    <link rel="shortcut icon" href="/blog/img/title.png">
    <link rel="stylesheet" href="//unpkg.com/hexo-theme-material-indigo@latest/css/style.css">
    <script>window.lazyScripts=[]</script>

    <!-- custom head -->
    

<meta name="generator" content="Hexo 4.2.0"></head>

<body>
    <div id="loading" class="active"></div>

    <aside id="menu" class="hide" >
  <div class="inner flex-row-vertical">
    <a href="javascript:;" class="header-icon waves-effect waves-circle waves-light" id="menu-off">
        <i class="icon icon-lg icon-close"></i>
    </a>
    <div class="brand-wrap" style="background-image:url(/blog/img/brand.jpg)">
      <div class="brand">
        <a href="/blog/" class="avatar waves-effect waves-circle waves-light">
          <img src="/blog/img/avatar.jpg">
        </a>
        <hgroup class="introduce">
          <h5 class="nickname">特务依昂</h5>
          <a href="mailto:1131564805@qq.com" title="1131564805@qq.com" class="mail">1131564805@qq.com</a>
        </hgroup>
      </div>
    </div>
    <div class="scroll-wrap flex-col">
      <ul class="nav">
        
            <li class="waves-block waves-effect">
              <a href="/blog/"  >
                <i class="icon icon-lg icon-home"></i>
                主页
              </a>
            </li>
        
            <li class="waves-block waves-effect">
              <a href="/blog/archives"  >
                <i class="icon icon-lg icon-archives"></i>
                博客
              </a>
            </li>
        
            <li class="waves-block waves-effect">
              <a href="/blog/tags"  >
                <i class="icon icon-lg icon-tags"></i>
                标签
              </a>
            </li>
        
            <li class="waves-block waves-effect">
              <a href="/blog/categories"  >
                <i class="icon icon-lg icon-th-list"></i>
                分类
              </a>
            </li>
        
            <li class="waves-block waves-effect">
              <a href="https://github.com/tewuyiang" target="_blank" >
                <i class="icon icon-lg icon-github"></i>
                Github
              </a>
            </li>
        
            <li class="waves-block waves-effect">
              <a href="https://weibo.com/u/5516635708/" target="_blank" >
                <i class="icon icon-lg icon-weibo"></i>
                Weibo
              </a>
            </li>
        
            <li class="waves-block waves-effect">
              <a href="https://www.cnblogs.com/tuyang1129/" target="_blank" >
                <i class="icon icon-lg icon-link"></i>
                博客园
              </a>
            </li>
        
      </ul>
    </div>
  </div>
</aside>

    <main id="main">
        <header class="top-header" id="header">
    <div class="flex-row">
        <a href="javascript:;" class="header-icon waves-effect waves-circle waves-light on" id="menu-toggle">
          <i class="icon icon-lg icon-navicon"></i>
        </a>
        <div class="flex-col header-title ellipsis">JVM基础——类加载器与双亲委派模型</div>
        
        <div class="search-wrap" id="search-wrap">
            <a href="javascript:;" class="header-icon waves-effect waves-circle waves-light" id="back">
                <i class="icon icon-lg icon-chevron-left"></i>
            </a>
            <input type="text" id="key" class="search-input" autocomplete="off" placeholder="输入感兴趣的关键字">
            <a href="javascript:;" class="header-icon waves-effect waves-circle waves-light" id="search">
                <i class="icon icon-lg icon-search"></i>
            </a>
        </div>
        
        
        <a href="javascript:;" class="header-icon waves-effect waves-circle waves-light" id="menuShare">
            <i class="icon icon-lg icon-share-alt"></i>
        </a>
        
    </div>
</header>
<header class="content-header post-header">

    <div class="container fade-scale">
        <h1 class="title">JVM基础——类加载器与双亲委派模型</h1>
        <h5 class="subtitle">
            
                <time datetime="2020-03-17T14:46:06.000Z" itemprop="datePublished" class="page-time">
  2020-03-17
</time>


	<ul class="article-category-list"><li class="article-category-list-item"><a class="article-category-list-link" href="/blog/categories/JVM/">JVM</a></li></ul>

            
        </h5>
    </div>

    


</header>


<div class="container body-wrap">
    
    <aside class="post-widget">
        <nav class="post-toc-wrap post-toc-shrink" id="post-toc">
            <h4>TOC</h4>
            <ol class="post-toc"><li class="post-toc-item post-toc-level-2"><a class="post-toc-link" href="#一、前言"><span class="post-toc-number">1.</span> <span class="post-toc-text">一、前言</span></a></li><li class="post-toc-item post-toc-level-2"><a class="post-toc-link" href="#二、正文"><span class="post-toc-number">2.</span> <span class="post-toc-text">二、正文</span></a><ol class="post-toc-child"><li class="post-toc-item post-toc-level-3"><a class="post-toc-link" href="#emsp-2-1-什么是类加载器"><span class="post-toc-number">2.1.</span> <span class="post-toc-text">&amp;emsp;2.1 什么是类加载器</span></a></li><li class="post-toc-item post-toc-level-3"><a class="post-toc-link" href="#emsp-2-2-类加载器的分类"><span class="post-toc-number">2.2.</span> <span class="post-toc-text">&amp;emsp;2.2 类加载器的分类</span></a></li><li class="post-toc-item post-toc-level-3"><a class="post-toc-link" href="#emsp-2-3-双亲委派模型"><span class="post-toc-number">2.3.</span> <span class="post-toc-text">&amp;emsp;2.3 双亲委派模型</span></a></li></ol></li><li class="post-toc-item post-toc-level-2"><a class="post-toc-link" href="#三、总结"><span class="post-toc-number">3.</span> <span class="post-toc-text">三、总结</span></a></li><li class="post-toc-item post-toc-level-2"><a class="post-toc-link" href="#四、参考"><span class="post-toc-number">4.</span> <span class="post-toc-text">四、参考</span></a></li></ol>
        </nav>
    </aside>


<article id="post-JVM基础——类加载器与双亲委派模型"
  class="post-article article-type-post fade" itemprop="blogPost">

    <div class="post-card">
        <h1 class="post-card-title">JVM基础——类加载器与双亲委派模型</h1>
        <div class="post-meta">
            <time class="post-time" title="2020-03-17 22:46:06" datetime="2020-03-17T14:46:06.000Z"  itemprop="datePublished">2020-03-17</time>

            
	<ul class="article-category-list"><li class="article-category-list-item"><a class="article-category-list-link" href="/blog/categories/JVM/">JVM</a></li></ul>



            
<span id="busuanzi_container_page_pv" title="文章总阅读量" style='display:none'>
    <i class="icon icon-eye icon-pr"></i><span id="busuanzi_value_page_pv"></span>
</span>


        </div>
        <div class="post-content" id="post-content" itemprop="postContent">
            <h2 id="一、前言"><a href="#一、前言" class="headerlink" title="一、前言"></a>一、前言</h2><p>&emsp;&emsp;这是<code>JVM</code>系列博客的第五篇，也是最后一篇，写完这篇博客，我就要暂时停止对<code>JVM</code>的学习，开始学习其他方面的内容了。这篇博客就来说一说<code>JVM</code>中的类加载器，以及类加载的双亲委派模型。</p>
<br>

<h2 id="二、正文"><a href="#二、正文" class="headerlink" title="二、正文"></a>二、正文</h2><h3 id="emsp-2-1-什么是类加载器"><a href="#emsp-2-1-什么是类加载器" class="headerlink" title="&emsp;2.1 什么是类加载器"></a>&emsp;2.1 什么是类加载器</h3><p>&emsp;&emsp;首先我们要知道一件事，那就是什么是类加载器？大家都知道，我们编写的代码需要先被编译为<code>class</code>字节码才能被执行，<code>JVM</code>解释器只能识别字节码，而不能执行<code>Java</code>源代码。而程序都是在内存中执行的，所以，为了能够执行字节码，就需要将它读取到内存中。将字节码读取到内存中这个工作，就是由类加载器来完成的。类加载器根据提供的全限定类名（包名+类名），找到对应路径下的类的<code>class</code>文件，将其读取到<code>JVM</code>管理的方法区中，这样才能执行其中的代码指令，访问类中的数据。关于类加载机制，可以参考这篇博客：<a href="https://www.cnblogs.com/tuyang1129/p/12514174.html" target="_blank" rel="noopener">JVM基础——分析类的加载过程</a>。</p>
<p>&emsp;&emsp;对于类加载器，需要注意一个问题。每一个类都是由它本身和类加载器一同来确定唯一性。这是什么意思？这就是说，<strong>如果一个类的字节码，分别使用两个不同的类加载器进行加载，则对于JVM来说，会将这两次加载识别为不同的两个类</strong>。举个例子，我们有一个类<code>Test</code>，创建了一个自定义的类加载器去加载它，并通过自定义的类加载器得到的<code>Class</code>对象创建<code>Test</code>对象<code>t</code>（反射），此时运行<code>t instanceof Test</code>，得到的将是<code>false</code>。因为这个对象是通过自定义类加载器加载的<code>Test</code>创建，而<code>intanceof</code>语句中的<code>Test</code>是<code>JVM</code>类加载器加载的<code>Test</code>，对于<code>JVM</code>来说，这是两个不同的类。除此之外，<strong>对于拥有相同全限定名的类，同一个类加载器只会加载一次，不会重复加载</strong>。</p>
<br>

<h3 id="emsp-2-2-类加载器的分类"><a href="#emsp-2-2-类加载器的分类" class="headerlink" title="&emsp;2.2 类加载器的分类"></a>&emsp;2.2 类加载器的分类</h3><p>&emsp;&emsp;在<code>Java</code>中，类加载器一般分为四类，分别是：</p>
<ul>
<li>启动类加载器（Bootstrap ClassLoader）；</li>
<li>扩展类加载器（Extension ClassLoader）；</li>
<li>应用程序类加载器（Application ClassLoader）；</li>
<li>自定义类加载器（User ClassLoader）；</li>
</ul>
<p>&emsp;&emsp;下面就来分别介绍一下这四种不同的类加载器。</p>
<br>

<p>&emsp;<strong>（1）启动类加载器（Bootstrap ClassLoader）</strong></p>
<p>&emsp;&emsp;启动类加载器不是由<code>Java</code>语言实现，而是由<code>C++</code>实现的（HotSpot虚拟机中），它负责加载<code>%JAVA_HOME%\lib</code>目录下的类，比如<code>String</code>，<code>Integer</code>，<code>HashMap</code>…….这些类都是放在这个目录下，所以都是由启动类加载器加载。除此之外，<code>JVM</code>还提供了一个配置参数<code>-Xbootclasspath</code>，这个参数指定的目录下的类文件（如<code>jar</code>包，<code>class</code>文件），也会被启动类加载器加载。由于这个类加载器是由<code>C++</code>实现，所以它并不属于<code>Java</code>的一部分，而是虚拟机的一部分，不能在<code>Java</code>代码中直接引用。通过下面的代码可以尝试获得<code>String</code>类的类加载器，也就是启动类加载器，但是输出结果为<code>null</code>，因为它不属于<code>Java</code>的一部分：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">    ClassLoader c = String<span class="class">.<span class="keyword">class</span>.<span class="title">getClassLoader</span>()</span>;</span><br><span class="line">    System.out.println(c);  <span class="comment">// 输出null</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<br>

<p>&emsp;<strong>（2）扩展类加载器（Extension ClassLoader）</strong></p>
<p>&emsp;&emsp;扩展类加载器是由<code>Java</code>实现的，实现类是<code>sun.misc.Launcher$ExtClassLoader</code>（名字可以看出这是一个内部类），这个类加载器负责加载<code>%JAVA_HOME%\lib\ext</code>目录下的类。由于这个类加载器是由<code>Java</code>实现，所以可以直接在<code>Java</code>程序中引用。我们可以通过一个<code>%JAVA_HOME%\lib\ext</code>目录下的类的<code>Class</code>对象来获得这个类加载器，也可以通过下面这种方式获得（以下方法基于双亲委派模型，后面解释）：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">    <span class="comment">// 获得自己写的类的加载器</span></span><br><span class="line">    ClassLoader c = Main<span class="class">.<span class="keyword">class</span>.<span class="title">getClassLoader</span>()</span>;</span><br><span class="line">    <span class="comment">// Main加载器的父加载器就是扩展类加载器</span></span><br><span class="line">    ClassLoader c2 = c.getParent();</span><br><span class="line">    <span class="comment">// 输出：sun.misc.Launcher$ExtClassLoader@eed1f14</span></span><br><span class="line">    System.out.println(c2);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<br>

<p>&emsp;<strong>（3）应用程序类加载器（Application ClassLoader）</strong></p>
<p>&emsp;&emsp;这个类加载期也是由<code>Java</code>语言实现的，实现类是<code>sun.misc.Launcher$AppClassLoader</code>，从<code>$</code>符号可以看出，这也是一个内部类。它负责加载类路径（<code>CLASSPATH</code>）下的类库，而我们编写的代码也是属于这个路径下的（<code>CLASSPATH</code>包含当前所在路径）。所以，当我们自己编写的<code>Java</code>代码没有指定类加载器，则默认使用这个加载器进行加载。由于这个类加载器是<code>Java</code>实现，所以也可以在我们的代码中引用，引用方法如下：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">    <span class="comment">// 方式1：使用自定义类的Class对象获得</span></span><br><span class="line">    ClassLoader c1 = Main<span class="class">.<span class="keyword">class</span>.<span class="title">getClassLoader</span>()</span>;</span><br><span class="line">    <span class="comment">// 方式2：使用ClassLoader类的getSystemClassLoader方法获得</span></span><br><span class="line">    ClassLoader c2 = ClassLoader.getSystemClassLoader();</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 输出：sun.misc.Launcher$AppClassLoader@18b4aac2</span></span><br><span class="line">    System.out.println(c1);</span><br><span class="line">    <span class="comment">// 输出：true</span></span><br><span class="line">    System.out.println(c1 == c2);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<br>

<p>&emsp;<strong>（4）自定义类加载器（User ClassLoader）</strong></p>
<p>&emsp;&emsp;根据需要，我们可以编写自己的类加载器，而自己编写的类加载器就称为自定义加载器。编写自定义类加载器的方式很简单：继承<code>ClassLoader</code>类，然后重写其中的方法即可。对于<code>Java</code>实现的类加载器，都是调用其中的<code>loadClass()</code>方法对类进行加载的，所以我们可以重写这个方法，但是这种做法不推荐，因为这样容易破坏类的加载机制（之后会讲到的双亲委派模型）。最好的做法是重写<code>findClass()</code>方法，这个方法会在<code>loadClass()</code>中被调用。在<code>findClass()</code>方法中，读取需要加载的类的<code>class</code>文件，转换成一个字节数组，再调用父类的<code>defineClass</code>方法将字节数组转换为<code>Class</code>对象返回即可，如下所示：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 自定义类加载器，实现ClassLoader</span></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">MyClassLoader</span> <span class="keyword">extends</span> <span class="title">ClassLoader</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//指定class文件的路径路径</span></span><br><span class="line">    <span class="keyword">private</span> String path;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">MyClassLoader</span><span class="params">(String classPath)</span> </span>&#123;</span><br><span class="line">        path = classPath;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 重写findClass方法</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> name 是我们这个类的全路径</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">protected</span> Class&lt;?&gt; findClass(String name) <span class="keyword">throws</span> ClassNotFoundException &#123;</span><br><span class="line">        Class log = <span class="keyword">null</span>;</span><br><span class="line">        <span class="comment">// 获取该class文件字节码数组</span></span><br><span class="line">        <span class="keyword">byte</span>[] classData = getData();</span><br><span class="line"></span><br><span class="line">        <span class="keyword">if</span> (classData == <span class="keyword">null</span>) &#123;</span><br><span class="line">            <span class="keyword">throw</span> <span class="keyword">new</span> ClassNotFoundException(<span class="string">"Class Not Found"</span>);</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="comment">// 将class的字节码数组转换成Class类的实例，并返回</span></span><br><span class="line">        <span class="keyword">return</span> defineClass(name, classData, <span class="number">0</span>, classData.length);;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 读取class，将字节码转换成字节数组</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@return</span></span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">byte</span>[] getData() &#123;</span><br><span class="line">        <span class="comment">// 省略读取的代码</span></span><br><span class="line">        <span class="comment">// 普通IO读取即可</span></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<br>

<h3 id="emsp-2-3-双亲委派模型"><a href="#emsp-2-3-双亲委派模型" class="headerlink" title="&emsp;2.3 双亲委派模型"></a>&emsp;2.3 双亲委派模型</h3><figure class="image-bubble">
                <div class="img-lightbox">
                    <div class="overlay"></div>
                    <img src="1.png" alt="" title="">
                </div>
                <div class="image-caption"></div>
            </figure>

<p>&emsp;&emsp;上面这张图所对应的关系，就被称为类加载器的双亲委派模型。对于每一个类加载器，都有一个父加载器（除了启动类加载器）。当类加载器需要加载一个类时，它首先会将这个类委托给它的父加载器进行加载，若这个父加载器也有父加载器，则继续向上委托，一直到启动类加载器。启动类加载器尝试加载这个类，若这个类在自己管理的目录之下，且还没有被加载，则成功加载，否则加载失败；若加载失败，则交给下层的扩展类加载器进行加载，而扩展类加载器也进行同样的操作。总的来说，<strong>双亲委派模型就是先将类交给父类加载器尝试加载，若加载失败，再由子类来加载，每一层都是如此</strong>。而在实际实现中，这种父子关系并不是由继承实现，而是由<strong>组合</strong>实现，在<code>ClassLoader</code>类中，有一个属性，名叫<code>parent</code>，就是指向它的父加载器的引用（之前的扩展类加载器代码就是这样得到的）。</p>
<p>&emsp;&emsp;下面我们是<code>ClassLoader</code>类的<code>loadClass</code>方法源码，看看双亲委派模型的具体实现代码：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// name为类的全限定类名</span></span><br><span class="line"><span class="keyword">public</span> Class&lt;?&gt; loadClass(String name) <span class="keyword">throws</span> ClassNotFoundException &#123;</span><br><span class="line">    <span class="keyword">return</span> loadClass(name, <span class="keyword">false</span>);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 这个重载方法被上面的方法调用</span></span><br><span class="line"><span class="keyword">protected</span> Class&lt;?&gt; loadClass(String name, <span class="keyword">boolean</span> resolve) </span><br><span class="line">    <span class="keyword">throws</span> ClassNotFoundException &#123;</span><br><span class="line">    </span><br><span class="line">    <span class="comment">// 对以下代码进行多线程同步</span></span><br><span class="line">    <span class="keyword">synchronized</span> (getClassLoadingLock(name)) &#123;</span><br><span class="line">        <span class="comment">// 首先，判断这个类是否已经被加载</span></span><br><span class="line">        Class&lt;?&gt; c = findLoadedClass(name);</span><br><span class="line"></span><br><span class="line">        <span class="comment">// c为null表示还没有被加载，则进行加载</span></span><br><span class="line">        <span class="keyword">if</span> (c == <span class="keyword">null</span>) &#123;</span><br><span class="line">            <span class="keyword">long</span> t0 = System.nanoTime();</span><br><span class="line">            <span class="keyword">try</span> &#123;</span><br><span class="line">                <span class="comment">// 此处是双亲委托机制的关键</span></span><br><span class="line">                <span class="comment">// 如果当前加载器有父加载器</span></span><br><span class="line">                <span class="keyword">if</span> (parent != <span class="keyword">null</span>) &#123;</span><br><span class="line">                    <span class="comment">// 调用父加载器的loadClass对类进行加载</span></span><br><span class="line">                    c = parent.loadClass(name, <span class="keyword">false</span>);</span><br><span class="line">                &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">                    <span class="comment">// 若没有父类加载器，则调用引导类加载器尝试加载</span></span><br><span class="line">                    c = findBootstrapClassOrNull(name);</span><br><span class="line">                &#125;</span><br><span class="line">            &#125; <span class="keyword">catch</span> (ClassNotFoundException e) &#123;</span><br><span class="line">                <span class="comment">// 此时加载失败将抛出异常，提示类找不到</span></span><br><span class="line">                <span class="comment">// 不需要处理，继续执行</span></span><br><span class="line">            &#125;</span><br><span class="line"></span><br><span class="line">            <span class="comment">// c为null表示调用上层类加载器加载失败</span></span><br><span class="line">            <span class="keyword">if</span> (c == <span class="keyword">null</span>) &#123;</span><br><span class="line">                <span class="keyword">long</span> t1 = System.nanoTime();</span><br><span class="line">                <span class="comment">// 调用当前类加载器的findClass进行加载</span></span><br><span class="line">                <span class="comment">// 所以自定义类加载器推荐重写findClass方法</span></span><br><span class="line">                c = findClass(name);</span><br><span class="line"></span><br><span class="line">                <span class="comment">// this is the defining class loader; record the stats</span></span><br><span class="line">                sun.misc.PerfCounter.getParentDelegationTime().addTime(t1 - t0);</span><br><span class="line">                sun.misc.PerfCounter.getFindClassTime().addElapsedTimeFrom(t1);</span><br><span class="line">                sun.misc.PerfCounter.getFindClasses().increment();</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">if</span> (resolve) &#123;</span><br><span class="line">            resolveClass(c);</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> c;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>&emsp;&emsp;通过上面的代码我们可以清楚地看到双亲委派机制是如何实现的。那这种机制有什么好处呢？使用双亲委派机制可以确保类是被第一个满足条件的类加载器所加载。而对于一个类加载器来说，每一个类只会加载一次，所以不会造成同一个类加载多次，或者一个类被不同的类加载器所加载的情况。之前说过，类的唯一性是由它的本身和加载它的类加载器确定的，使用双亲委派模型很好地避免了类被多个加载器加载，导致在内存中出现相同却不等价的类。比如说我们也定义一个<code>java.lang.String</code>类，如果没有双亲委派模型，内存中将出现两个<code>String</code>，但是在我们看来只有一个，此时将会导致程序产生莫名其妙的错误。而双亲委派模型保证了这种同名的类永远没有办法被加载运行，所以我们自己定义的重名类将永远无法使用，虽然编译可以通过（这里可以自己去试试）。</p>
<p>&emsp;&emsp;当然，双亲委派模型并不是<code>JVM</code>规范中强制要求的，而是一种推荐的策略。所以我们完全可以在编写自己的类加载器时不遵守这个模型，比如重写<code>loadClass</code>方法覆盖这个机制。但是如果不是必要，还是不推荐这么做。</p>
<br>

<h2 id="三、总结"><a href="#三、总结" class="headerlink" title="三、总结"></a>三、总结</h2><p>&emsp;&emsp;关于类加载器和双亲委派模型就先说这么多吧。上面对这两部分内容做了一个还算具体的描述，相信看完之后会对<code>Java</code>的一些相关特性有更加深入的理解，也能解决我们平常的一些疑惑。</p>
<br>

<h2 id="四、参考"><a href="#四、参考" class="headerlink" title="四、参考"></a>四、参考</h2><ul>
<li>《深入理解Java虚拟机》</li>
</ul>

        </div>

        <blockquote class="post-copyright">
    
    <div class="content">
        
<span class="post-time">
    最后更新时间：<time datetime="2020-03-18T12:02:16.971Z" itemprop="dateUpdated">2020-03-18 20:02:16</time>
</span><br>


        
        世界是个球，前方总有路！
        
    </div>
    
    <footer>
        <a href="http://tewuyiang.gitee.io/blog">
            <img src="/blog/img/avatar.jpg" alt="特务依昂">
            特务依昂
        </a>
    </footer>
</blockquote>

        


        <div class="post-footer">
            
	<ul class="article-tag-list" itemprop="keywords"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/blog/tags/JVM/" rel="tag">JVM</a></li></ul>


            
<div class="page-share-wrap">
    

<div class="page-share" id="pageShare">
    <ul class="reset share-icons">
      <li>
        <a class="weibo share-sns" target="_blank" href="http://service.weibo.com/share/share.php?url=http://tewuyiang.gitee.io/blog/JVM%E5%9F%BA%E7%A1%80%E2%80%94%E2%80%94%E7%B1%BB%E5%8A%A0%E8%BD%BD%E5%99%A8%E4%B8%8E%E5%8F%8C%E4%BA%B2%E5%A7%94%E6%B4%BE%E6%A8%A1%E5%9E%8B/&title=《JVM基础——类加载器与双亲委派模型》 — 博客主页&pic=http://tewuyiang.gitee.io/blog/img/avatar.jpg" data-title="微博">
          <i class="icon icon-weibo"></i>
        </a>
      </li>
      <li>
        <a class="weixin share-sns wxFab" href="javascript:;" data-title="微信">
          <i class="icon icon-weixin"></i>
        </a>
      </li>
      <li>
        <a class="qq share-sns" target="_blank" href="http://connect.qq.com/widget/shareqq/index.html?url=http://tewuyiang.gitee.io/blog/JVM%E5%9F%BA%E7%A1%80%E2%80%94%E2%80%94%E7%B1%BB%E5%8A%A0%E8%BD%BD%E5%99%A8%E4%B8%8E%E5%8F%8C%E4%BA%B2%E5%A7%94%E6%B4%BE%E6%A8%A1%E5%9E%8B/&title=《JVM基础——类加载器与双亲委派模型》 — 博客主页&source=一个未来程序员的博客~~~" data-title=" QQ">
          <i class="icon icon-qq"></i>
        </a>
      </li>
      <li>
        <a class="facebook share-sns" target="_blank" href="https://www.facebook.com/sharer/sharer.php?u=http://tewuyiang.gitee.io/blog/JVM%E5%9F%BA%E7%A1%80%E2%80%94%E2%80%94%E7%B1%BB%E5%8A%A0%E8%BD%BD%E5%99%A8%E4%B8%8E%E5%8F%8C%E4%BA%B2%E5%A7%94%E6%B4%BE%E6%A8%A1%E5%9E%8B/" data-title=" Facebook">
          <i class="icon icon-facebook"></i>
        </a>
      </li>
      <li>
        <a class="twitter share-sns" target="_blank" href="https://twitter.com/intent/tweet?text=《JVM基础——类加载器与双亲委派模型》 — 博客主页&url=http://tewuyiang.gitee.io/blog/JVM%E5%9F%BA%E7%A1%80%E2%80%94%E2%80%94%E7%B1%BB%E5%8A%A0%E8%BD%BD%E5%99%A8%E4%B8%8E%E5%8F%8C%E4%BA%B2%E5%A7%94%E6%B4%BE%E6%A8%A1%E5%9E%8B/&via=http://tewuyiang.gitee.io/blog" data-title=" Twitter">
          <i class="icon icon-twitter"></i>
        </a>
      </li>
      <li>
        <a class="google share-sns" target="_blank" href="https://plus.google.com/share?url=http://tewuyiang.gitee.io/blog/JVM%E5%9F%BA%E7%A1%80%E2%80%94%E2%80%94%E7%B1%BB%E5%8A%A0%E8%BD%BD%E5%99%A8%E4%B8%8E%E5%8F%8C%E4%BA%B2%E5%A7%94%E6%B4%BE%E6%A8%A1%E5%9E%8B/" data-title=" Google+">
          <i class="icon icon-google-plus"></i>
        </a>
      </li>
    </ul>
 </div>



    <a href="javascript:;" id="shareFab" class="page-share-fab waves-effect waves-circle">
        <i class="icon icon-share-alt icon-lg"></i>
    </a>
</div>



        </div>
    </div>

    
<nav class="post-nav flex-row flex-justify-between">
  
    <div class="waves-block waves-effect prev">
      <a href="/blog/%E6%B7%B1%E5%85%A5%E7%90%86%E8%A7%A3Java%E6%96%B9%E6%B3%95%E9%87%8D%E8%BD%BD%E7%9A%84%E5%AE%9E%E7%8E%B0%E5%8E%9F%E7%90%86/" id="post-prev" class="post-nav-link">
        <div class="tips"><i class="icon icon-angle-left icon-lg icon-pr"></i> Prev</div>
        <h4 class="title">深入理解Java中方法重载的实现原理</h4>
      </a>
    </div>
  

  
    <div class="waves-block waves-effect next">
      <a href="/blog/JVM%E5%9F%BA%E7%A1%80%E2%80%94%E2%80%94%E6%B5%85%E6%9E%90%E7%B1%BB%E7%9A%84%E5%8A%A0%E8%BD%BD%E8%BF%87%E7%A8%8B/" id="post-next" class="post-nav-link">
        <div class="tips">Next <i class="icon icon-angle-right icon-lg icon-pl"></i></div>
        <h4 class="title">JVM基础——浅析类的加载过程</h4>
      </a>
    </div>
  
</nav>



    




















</article>



</div>

        <footer class="footer">
    <div class="top">
        
<p>
    <span id="busuanzi_container_site_uv" style='display:none'>
        站点总访客数：<span id="busuanzi_value_site_uv"></span>
    </span>
    <span id="busuanzi_container_site_pv" style='display:none'>
        站点总访问量：<span id="busuanzi_value_site_pv"></span>
    </span>
</p>


        <p>
            
                <span><a href="/blog/atom.xml" target="_blank" class="rss" title="rss"><i class="icon icon-lg icon-rss"></i></a></span>
            
            <span>博客内容遵循 <a rel="license noopener" href="https://creativecommons.org/licenses/by-nc-sa/4.0/deed.zh" target="_blank">知识共享 署名 - 非商业性 - 相同方式共享 4.0 国际协议</a></span>
        </p>
    </div>
    <div class="bottom">
        <p><span>特务依昂 &copy; 2015 - 2020</span>
            <span>
                
                Power by <a href="http://hexo.io/" target="_blank">Hexo</a> Theme <a href="https://github.com/yscoder/hexo-theme-indigo" target="_blank">indigo</a>
            </span>
        </p>
    </div>
</footer>

    </main>
    <div class="mask" id="mask"></div>
<a href="javascript:;" id="gotop" class="waves-effect waves-circle waves-light"><span class="icon icon-lg icon-chevron-up"></span></a>



<div class="global-share" id="globalShare">
    <ul class="reset share-icons">
      <li>
        <a class="weibo share-sns" target="_blank" href="http://service.weibo.com/share/share.php?url=http://tewuyiang.gitee.io/blog/JVM%E5%9F%BA%E7%A1%80%E2%80%94%E2%80%94%E7%B1%BB%E5%8A%A0%E8%BD%BD%E5%99%A8%E4%B8%8E%E5%8F%8C%E4%BA%B2%E5%A7%94%E6%B4%BE%E6%A8%A1%E5%9E%8B/&title=《JVM基础——类加载器与双亲委派模型》 — 博客主页&pic=http://tewuyiang.gitee.io/blog/img/avatar.jpg" data-title="微博">
          <i class="icon icon-weibo"></i>
        </a>
      </li>
      <li>
        <a class="weixin share-sns wxFab" href="javascript:;" data-title="微信">
          <i class="icon icon-weixin"></i>
        </a>
      </li>
      <li>
        <a class="qq share-sns" target="_blank" href="http://connect.qq.com/widget/shareqq/index.html?url=http://tewuyiang.gitee.io/blog/JVM%E5%9F%BA%E7%A1%80%E2%80%94%E2%80%94%E7%B1%BB%E5%8A%A0%E8%BD%BD%E5%99%A8%E4%B8%8E%E5%8F%8C%E4%BA%B2%E5%A7%94%E6%B4%BE%E6%A8%A1%E5%9E%8B/&title=《JVM基础——类加载器与双亲委派模型》 — 博客主页&source=一个未来程序员的博客~~~" data-title=" QQ">
          <i class="icon icon-qq"></i>
        </a>
      </li>
      <li>
        <a class="facebook share-sns" target="_blank" href="https://www.facebook.com/sharer/sharer.php?u=http://tewuyiang.gitee.io/blog/JVM%E5%9F%BA%E7%A1%80%E2%80%94%E2%80%94%E7%B1%BB%E5%8A%A0%E8%BD%BD%E5%99%A8%E4%B8%8E%E5%8F%8C%E4%BA%B2%E5%A7%94%E6%B4%BE%E6%A8%A1%E5%9E%8B/" data-title=" Facebook">
          <i class="icon icon-facebook"></i>
        </a>
      </li>
      <li>
        <a class="twitter share-sns" target="_blank" href="https://twitter.com/intent/tweet?text=《JVM基础——类加载器与双亲委派模型》 — 博客主页&url=http://tewuyiang.gitee.io/blog/JVM%E5%9F%BA%E7%A1%80%E2%80%94%E2%80%94%E7%B1%BB%E5%8A%A0%E8%BD%BD%E5%99%A8%E4%B8%8E%E5%8F%8C%E4%BA%B2%E5%A7%94%E6%B4%BE%E6%A8%A1%E5%9E%8B/&via=http://tewuyiang.gitee.io/blog" data-title=" Twitter">
          <i class="icon icon-twitter"></i>
        </a>
      </li>
      <li>
        <a class="google share-sns" target="_blank" href="https://plus.google.com/share?url=http://tewuyiang.gitee.io/blog/JVM%E5%9F%BA%E7%A1%80%E2%80%94%E2%80%94%E7%B1%BB%E5%8A%A0%E8%BD%BD%E5%99%A8%E4%B8%8E%E5%8F%8C%E4%BA%B2%E5%A7%94%E6%B4%BE%E6%A8%A1%E5%9E%8B/" data-title=" Google+">
          <i class="icon icon-google-plus"></i>
        </a>
      </li>
    </ul>
 </div>


<div class="page-modal wx-share" id="wxShare">
    <a class="close" href="javascript:;"><i class="icon icon-close"></i></a>
    <p>扫一扫，分享到微信</p>
    <img src="" alt="微信分享二维码">
</div>




    <script src="//cdn.bootcss.com/node-waves/0.7.4/waves.min.js"></script>
<script>
var BLOG = { ROOT: '/blog/', SHARE: true, REWARD: false };


</script>

<script src="//unpkg.com/hexo-theme-material-indigo@latest/js/main.min.js"></script>


<div class="search-panel" id="search-panel">
    <ul class="search-result" id="search-result"></ul>
</div>
<template id="search-tpl">
<li class="item">
    <a href="{path}" class="waves-block waves-effect">
        <div class="title ellipsis" title="{title}">{title}</div>
        <div class="flex-row flex-middle">
            <div class="tags ellipsis">
                {tags}
            </div>
            <time class="flex-col time">{date}</time>
        </div>
    </a>
</li>
</template>

<script src="//unpkg.com/hexo-theme-material-indigo@latest/js/search.min.js" async></script>






<script async src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>



<script>
(function() {
    var OriginTitile = document.title, titleTime;
    document.addEventListener('visibilitychange', function() {
        if (document.hidden) {
            document.title = '人呢，怎么不见了！';
            clearTimeout(titleTime);
        } else {
            document.title = '(つェ⊂)咦!欢迎回来!';
            titleTime = setTimeout(function() {
                document.title = OriginTitile;
            },2000);
        }
    });
})();
</script>



</body>
</html>
